<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="id">
        <el-input v-model="queryParams.id" placeholder="请输入品牌商ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入品牌商名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['brands:brand:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['brands:brand:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['brands:brand:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['brands:brand:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="brandList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="品牌商ID" align="center" prop="id" />
      <el-table-column label="品牌商名称" align="center" prop="name" />
      <el-table-column label="介绍" align="center" prop="desc" :show-overflow-tooltip="true" />
      <el-table-column label="品牌商图片" align="center" prop="picUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.picUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="底价" align="center" prop="floorPrice" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleTuiguang(scope.row)">推广码</el-button>

          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['brands:brand:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['brands:brand:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!--店铺推广码对话框-->
    <el-dialog title="店铺推广码" :visible.sync="tuiopen" width="600px" append-to-body>
      <h4 style='margin-left: 20px;'>推广二维码</h4>
      <img :src="imglist.img" style="width: 200px; height: 200px; margin-left: 100px;">
    </el-dialog>

    <!-- 添加或修改品牌商对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="品牌商名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌商名称" style="width: 300px;" />
        </el-form-item>

        <el-form-item label="主营类目">
          <el-select v-model="form.defaultCategoryId" placeholder="请选择">
            <el-option v-for="les in levels" :key="les.level" :label="les.value" :value="les.id"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="管理员">
          <el-select v-model="form.adminId" placeholder="请选择">
            <el-option v-for="les in adminlist" :key="les.id" :label="les.username" :value="les.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="介绍" prop="desc">
          <el-input v-model="form.desc" placeholder="请输入介绍" style="width: 300px;" />
        </el-form-item>
        <el-form-item label="品牌商图片" prop="picUrl">
          <image-upload v-model="form.picUrl" />
        </el-form-item>
        <el-form-item label="底价" prop="floorPrice">
          <el-input v-model="form.floorPrice" placeholder="请输入底价" style="width: 300px;" />
        </el-form-item>

        <!-- 提货时间设置 -->
        <el-form-item label="提货时间设置" prop="fetchTimeRules">
          <!-- 展示已有时段 -->
          <div v-for="(time, index) in parsedTimeList" :key="index" class="time-item">
            <span>{{ formatTimeSlot(time) }}</span>
            <el-button type="danger" icon="el-icon-delete" circle @click="removeTime(index)"></el-button>
          </div>

          <!-- 添加新时段 -->
          <div v-if="isAdding" class="time-picker-wrapper">
            <el-time-picker v-model="newTimeRange" is-range value-format="HH:mm" range-separator="至"
              start-placeholder="开始时间" end-placeholder="结束时间"></el-time-picker>
            <div style="margin-top: 10px">
              <el-button type="primary" size="mini" @click="confirmAdd">确认</el-button>
              <el-button size="mini" @click="cancelAdd">取消</el-button>
            </div>
          </div>

          <!-- 添加按钮 -->
          <el-button v-else type="primary" icon="el-icon-plus" @click="startAdding">添加时间段</el-button>

          <!-- 隐藏的真实表单字段 -->
          <el-input v-model="form.fetchTimeRules" type="hidden" />
        </el-form-item>

        <el-form-item label="自提地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入自提地址" style="width: 300px;" />
        </el-form-item>

        <el-form-item label="经纬度" prop="longitude">
          <div class="sho-flex">
            <span><el-input v-model="form.longitude" placeholder="请输入经度" style="width: 130px;" /> </span>
            <span><el-input v-model="form.latitude" placeholder="请输入纬度"
                style="width: 130px; margin-left: 10px;" /></span>
            <el-button type="primary" style="margin-left: 10px;" @click="showMapDialog">获取经纬度</el-button>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 地图获取经纬度对话框 -->
    <!-- 优化地图对话框样式 -->
    <el-dialog title="选择位置" :visible.sync="mapDialogVisible" width="90%" top="5vh" append-to-body>
      <div class="map-container">
        <div id="container" style="height: 70vh;"></div>
        <div class="coordinates-display">
          <el-input
            v-model="lnglat"
            placeholder="点击地图获取经纬度"
            readonly
            style="width: 300px; margin-top: 10px;"
          >
            <template slot="prepend">当前坐标</template>
          </el-input>
          <el-button
            type="primary"
            style="margin-left: 10px;"
            @click="confirmCoordinates"
          >确认选择</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<style scoped>
  .time-item {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .time-picker-wrapper {
    margin: 10px 0;
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  #map-container {
    width: 100%;
    height: 500px;
    min-height: 300px;
    /* 防止高度塌陷 */
  }

  /* 地图 */

  .map-container {
    position: relative;
    height: 70vh;
  }
  .coordinates-display {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 999;
    background: rgba(255, 255, 255, 0.9);
    padding: 10px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
  }

  #container {
    width: 100%;
    height: 100%;
    border-radius: 4px;
  }

  .input-card {
    padding: 10px;
    background: white;
    border-top: 1px solid #ccc;
  }

  .input-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }

  .input-item-prepend {
    margin-right: 10px;
  }

  .input-item-text {
    font-size: 14px;
    color: #333;
  }

  input[type="text"] {
    flex: 1;
    padding: 5px;
    font-size: 14px;
    border: 1px solid #ccc;
    border-radius: 4px;
  }
</style>
<script>
  import {
    listBrand,
    getBrand,
    delBrand,
    addBrand,
    updateBrand,
    listAdmins
  } from "@/api/emporium/brand";

  export default {

    name: "Brand",
    data() {
      return {
        map: null, // 地图实例
        lnglat: '116.512402,39.867054', // 默认经纬度
        mapDialogVisible: false,

        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 品牌商表格数据
        brandList: [],
        //管理员列表
        adminlist: [],
        // 弹出层标题
        title: "",
        //提货时间设置
        isAdding: false,
        newTimeRange: null,
        parsedTimeList: [],
        // 是否显示弹出层
        open: false,
        //是否弹出推广码
        tuiopen: false,
        imglist: {
          img: ""
        },

        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          id: null,
          name: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [{
            required: true,
            message: "品牌商名称不能为空",
            trigger: "blur"
          }],
        },

      };
    },
    created() {
      this.getList();
    },
    watch: {
      'form.fetchTimeRules': {
        immediate: true,
        handler(newVal) {
          this.parseTimeRules(newVal)
        }
      }
    },
    mounted() {

      this.initMap(); // 页面加载完成后初始化地图

    },
    methods: {
      /***********地图经纬度***************/
      // 新增方法
        showMapDialog() {
          this.mapDialogVisible = true;
          this.$nextTick(() => {
            this.initMap();
          });
        },
      initMap() {
          if (typeof AMap !== 'undefined') {
            this.createMap();
            return;
          }

          const script = document.createElement('script');
          script.src = `https://webapi.amap.com/maps?v=2.0&key=0a73778ac2becf7a89f1e0abd832d660&plugin=AMap.ControlBar,AMap.ToolBar`;
          script.onload = () => this.createMap();
          document.head.appendChild(script);
        },

        createMap() {
          this.map = new AMap.Map('container', {
            zoom: 17,
            viewMode: '3D',
            center: [113.021717, 25.769705],
          });

          // 添加控件
          new AMap.ControlBar({ position: { right: '10px', top: '10px' } }).addTo(this.map);
          new AMap.ToolBar({ position: { right: '40px', top: '110px' } }).addTo(this.map);

          // 点击地图事件
          this.map.on('click', (e) => {
            this.lnglat = `${e.lnglat.getLng().toFixed(6)},${e.lnglat.getLat().toFixed(6)}`;
          });
        },

        // 新增确认坐标方法
        confirmCoordinates() {
          if (this.lnglat) {
            const [longitude, latitude] = this.lnglat.split(',');
            this.form.longitude = parseFloat(longitude);
            this.form.latitude = parseFloat(latitude);
            this.mapDialogVisible = false;
          }
        },
        /*******************************************************/



      /** 查询品牌商列表 */
      getList() {
        this.loading = true;
        listBrand(this.queryParams).then(response => {
          this.brandList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
        listAdmins().then(response => {
          this.adminlist = response;
          console.log(this.adminlist)
        });
      },
      // 解析数据库字符串
      //提现时间设置**********************//
      parseTimeRules(timeStr) {
        try {
          const cleaned = timeStr
            .replace(/[“”\\]/g, '')
            .replace(/-/g, '-') // 统一分隔符
          this.parsedTimeList = JSON.parse(cleaned)
        } catch (e) {
          this.parsedTimeList = []
        }
      },
      // 格式化显示
      formatTimeSlot(time) {
        return time.replace(/-/g, ' - ')
      },

      // 添加时段
      startAdding() {
        this.isAdding = true
        this.newTimeRange = null
      },
      confirmAdd() {
        if (this.newTimeRange && this.newTimeRange.length === 2) {
          const [start, end] = this.newTimeRange
          this.parsedTimeList.push(`${start}-${end}`)
          this.updateFormValue()
        }
        this.isAdding = false
      },

      cancelAdd() {
        this.isAdding = false
      },

      // 删除时段
      removeTime(index) {
        this.parsedTimeList.splice(index, 1)
        this.updateFormValue()
      },
      // 更新表单值
      updateFormValue() {
        this.form.fetchTimeRules = JSON.stringify(this.parsedTimeList)
          .replace(/-/g, '-')
          .replace(/"/g, '\\"')
      },

      //***********************************************//

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          name: null,
          defaultCategoryId: null,
          adminId: null,
          desc: null,
          picUrl: null,
          sortOrder: null,
          floorPrice: null,
          fetchTimeRules: null,
          addTime: null,
          updateTime: null,
          shareUrl: null,
          deleted: null,
          commpany: null,
          autoUpdateGood: null,
          shopUrl: null,
          defaultPages: null,
          addPrecent: null,
          address: null,
          longitude: null,
          latitude: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加品牌商";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getBrand(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改品牌商";
        });
      },
      /*推广码操作*/
      handleTuiguang(row) {
        this.tuiopen = true;
        this.imglist.img = row.shareUrl
      },

      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateBrand(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addBrand(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除品牌商编号为"' + ids + '"的数据项？').then(function() {
          return delBrand(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('brands/brand/export', {
          ...this.queryParams
        }, `brand_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
